package com.levi.juc.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁  ReadWriteLock  读的时候不加锁，写的时候加锁
 */
public class ReadWriteLockTest {

    public static void main(String[] args) {
        MyCache myCache = new MyCache();


        //创建5个线程用于存值
        for (int i = 1; i <= 5; i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.put(temp + "", temp + "");
            }).start();
        }

        //创建5个线程用于取值
        for (int i = 1; i <= 5; i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.get(temp + "");
            }).start();
        }
    }
}

class MyCache {
    Map<String, String> map = new HashMap<>();
    /**
     * 创建读写锁
     */
    private ReadWriteLock lock = new ReentrantReadWriteLock();

    //  put 放值
    public void put(String key, String value) {
        //创建写入锁
        Lock lock = this.lock.writeLock();
        //获得写锁
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getId() + "开始写入数据");
            map.put(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放锁
            lock.unlock();
            System.out.println(Thread.currentThread().getId() + "写入完毕,释放锁");
        }
    }

    //get  取值
    public void get(String key) {
        Lock lock = this.lock.readLock();
        lock.lock();

        try {
            System.out.println(Thread.currentThread().getId() + "开始读取数据");
            map.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            System.out.println(Thread.currentThread().getId() + "读取完毕,释放锁");
        }
    }

}
